import mqtt, { MqttClient, IClientOptions} from 'mqtt';
import config from "./config";
import log from './logger';

// MQTT 服务器地址
const brokerUrl: string = 'mqtt://mq.wechain360.com'; // 你可以替换为你自己的 MQTT 服务器地址

// MQTT 连接选项
const options: IClientOptions = {
    username: 'client1', // 替换为你的用户名
    password: 'Hlsk@1234', // 替换为你的密码
    clientId: 'client_' + config.code + Math.random().toString(16).substring(2, 8) // 随机生成客户端 ID
};

// 创建 MQTT 客户端
const client: MqttClient = mqtt.connect(brokerUrl, options);

function mqttInit(){
    // 连接成功事件
    client.on('connect', () => {
        log.info('Connected to MQTT broker');
    });

    // 错误处理
    client.on('error', (err: Error) => {
        log.error('MQTT error:', err);
    });

    // 断开连接事件
    client.on('close', () => {
        log.info('Disconnected from MQTT broker');
    });
}

function sendMqtt(cameraName: string, location: string, temperature: number){
    // 要发布的数据
    // {
    //  "platformName": "长子",
    //  "name": "1号煤棚气体检测"
    //  "data":{
    //    "co_concentration@1#": value
    //  }
    // }
    const dataObj: any = {
        platformName: config.platformName,
        platformId: config.platformId,
        name: cameraName,
        data: {
            [`coal_temperature@${location}`]: temperature
        }
    };

    // 将数据转换为 JSON 字符串
    const message: string = JSON.stringify(dataObj);

    // 发布消息到主题
    // {控制器产品型号}/{设备code}/event/json
    const topic: string = `edge-node/${config.code}/event/json`;
    client.publish(topic, message, { qos: 0 }, (err) => {
        if (!err) {
            log.info(`Data published to topic ${topic}:`, message);
        } else {
            log.error('Failed to publish message:', err);
        }
    });
}

export {mqttInit, sendMqtt};